package cn.aitrox.ry.service.alg.service.impl;

import cn.aitrox.ry.bean.RespResult;
import cn.aitrox.ry.common.bean.JsonCallback;
import cn.aitrox.ry.enumtype.RespCodeEnum;
import cn.aitrox.ry.service.alg.config.AlgNacosProperties;
import cn.aitrox.ry.service.alg.dto.ultrasound.video.in.VideoTraceInDto;
import cn.aitrox.ry.service.alg.dto.ultrasound.video.out.VideoTraceOutDto;
import cn.aitrox.ry.service.alg.service.UltrasoundVideoService;
import cn.aitrox.ry.util.JSONUtil;
import cn.aitrox.ry.util.LogUtil;
import cn.aitrox.ry.util.NetUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;

@Service
public class UltrasoundVideoServiceImpl implements UltrasoundVideoService {

    private static final Logger LOG = LoggerFactory.getLogger(UltrasoundVideoServiceImpl.class);

    @Autowired
    private AlgNacosProperties nacosProp;

    @Override
    public RespResult<VideoTraceOutDto> videoTrace(VideoTraceInDto reqDto) {
        String reqJson = JSONUtil.toJson(reqDto, VideoTraceInDto.class);
        try {
            Integer code = this.doRequest(nacosProp.getVideoTraceUrl(), "video-trace", reqJson, new JsonCallback<Integer>() {
                @Override
                public Integer deserializer(String json) throws IOException {
                    return Integer.parseInt(json);
                }
            }, nacosProp.getConnTimeout(), nacosProp.getSocketTimeout());
            return RespResult.ok(new VideoTraceOutDto(code));
        } catch (Exception e) {
            LOG.error(LogUtil.genException(e, "超声视频追踪异常"), e);
            return RespResult.secByError(RespCodeEnum.ERROR.getCode(), "追踪失败，请重试");
        }
    }

    private <T> T doRequest(String url, String logTitle, String reqJson, JsonCallback<T> jsonCallback, Integer connectTimeout, Integer socketTimeout) throws IOException {
        String responseStr = NetUtil.httpPostString(url, reqJson, null, "application/json", logTitle, connectTimeout, socketTimeout);
        return jsonCallback.deserializer(responseStr);
    }
}
